import { createSSRApp } from 'vue'
import * as Pinia from 'pinia'
import App from './App.vue'
import router from './router'


export function createApp() {
    const app = createSSRApp(App)

    // 初始化 Pinia
    const pinia = Pinia.createPinia()
    app.use(pinia)
    app.use(router)
    createBeforeEachGuard(router);
    createAfterEachGuard(router);
    return {
        app,
        Pinia
    }
}


export function createBeforeEachGuard(router) {
    console.log("router", router)
    router.beforeEach((to, from, next) => {
        const loginToken = getApp()?.loginToken;
        // 定义白名单：不需要登录的页面
        const whiteList = ['account_login','sms_login', 'register','newforgot','doctor_home'] // 根据实际路由name或path调整

        // 如果是白名单页面，直接放行
        if (whiteList.includes(to.name) || whiteList.includes(to.path) || to.path.indexOf("/tabPage/") !== -1) {
            next()
        }

        // 非白名单页面需要验证登录状态
        if (!loginToken) {
            // 未登录时跳转到登录页，同时记录当前路径用于登录后返回
            next({
                name: 'account_login',
                query: { redirect: to.fullPath } // 传递重定向参数
            })
        } else {
            // 已登录则正常跳转
            next()
        }
    })
}

export function createAfterEachGuard(router) {
    router.afterEach((to, from) => {
    })
}